<?
function drizzo_list_folder_contents($folder = 'drizzo-files') {
	$list = "<div id=\"table_wrap\">\n";
	$list .= "\t<table id=\"media_list\">\n";
	$list .= "\t\t<tr id=\"first\">\n";
	$list .= "\t\t\t<th>File</th>";
	if(drizzo_user_is_allowed('media-publish')) {
		$list .= "<th colspan=\"5\" class=\"center narrow\">Action</th>\n";
	} else {
		$list .= "\n";
	}
	$list .= "\t\t</tr>\n";
	$list .= drizzo_list_folder_contents_loop($folder);
	$list .= "\t</table>\n";
	$list .= "</div>";
	return $list;
}

function drizzo_list_folder_contents_loop($folder = 'drizzo-files', $alt_count = 0) {
	if(strpos($folder,"drizzo-files") === false && $folder != 'drizzo-files') {
		$dir = root_dir . "drizzo-files/" . $folder;
	} else {
		$dir = root_dir . $folder;
	}
	if($directory = opendir($dir)) {
		while(false !== ($file = readdir($directory))) {
			if($file != '.' && $file != '..') {
				$contents[] = $file;
			}
		}
		closedir($directory);
	}
	if(count($contents) > 0) {
		foreach($contents as $content) {
			if($alt_count%2) {
				$alt = " class=\"alt\"";
			} else {
				$alt = "";
			}
			$this_item = $dir . "/$content";
			$sub = (count(explode("/",str_replace(root_dir,"",$dir))) * 20) - 20;
			$bg_pos = ($sub + 10) . "px";
			$padding = ($sub + 30) . "px";
			if(is_file($this_item)) {
				$mime_type = explode("/",mime_content_type($dir . "/$content"));
				if($mime_type[1] == 'application') {
					$mime_type = $mime_type[1];
				} else {
					$mime_type = $mime_type[0];
				}
				$list .= "\t\t<tr$alt>\n";
				$list .= "\t\t\t<td class=\"file $mime_type\" style=\"background-position: $bg_pos center;padding-left: $padding;\"><a href=\"" . str_replace(root_dir,domain,$this_item) . "\" title=\"$content\">$content</a></td>";
				if(drizzo_user_is_allowed('media-publish')) {
					if($mime_type == 'image' && strpos($dir,"thumbs") === false && strpos($dir,"cache") === false) {
						$list .= "<td class=\"center\"><a href=\"media.php?action=create_thumb&amp;item=$this_item\" title=\"Create a Thumbnail for $content\" class=\"create_thumb_link\"><span>Create Thumbnail</span></a></td>";
					} else {
						$list .= "<td></td>";
					}
					if(strpos($dir,"cache") === false) {
						$list .= "<td><a href=\"media.php?action=replace&amp;item=$this_item\" title=\"Replace $content with a New Version\" class=\"replace_link\"><span>Replace</span></a></td>";
					} else {
						$list .= "<td></td>";
					}
					if(strpos($dir,"thumbs") === false && strpos($dir,"cache") === false) {
						$list .= "<td class=\"center\"><a href=\"media.php?action=move&amp;item=$this_item\" title=\"Move $content\" class=\"move_link\"><span>Move</span></a></td><td class=\"center\"><a href=\"media.php?action=rename&amp;item=$this_item\" title=\"Rename $content\" class=\"rename_link\"><span>Rename</span></a></td>";
					} else {
						$list .= "<td></td><td></td>";
					}
					$list .= "<td class=\"center\"><a href=\"media.php?action=delete&amp;item=$this_item\" title=\"Delete $content\" class=\"delete_link\"><span>Delete</span></a></td>\n";
				} else {
					$list .= "\n";
				}
				$list .= "\t\t</tr>\n";
				$alt_count++;
			} elseif(is_dir($this_item)) {
				$list .= "\t\t<tr$alt>\n";
				if($content == "thumbs" || $content == "cache") {
					$list .= "\t\t\t<td class=\"file folder\" style=\"background-position: $bg_pos center;padding-left: $padding;\"><em>$content</em></td>";
				} else {
					$list .= "\t\t\t<td class=\"file folder\" style=\"background-position: $bg_pos center;padding-left: $padding;\">$content</td>";
				}
				if(drizzo_user_is_allowed('media-publish')) {
					$list .= "<td></td><td></td>";
					if(strpos($this_item,"thumbs") === false && strpos($this_item,"cache") === false) {
						$list .= "<td class=\"center\"><a href=\"media.php?action=move&amp;item=$this_item\" title=\"Move $content\" class=\"move_link\"><span>Move</span></a></td><td class=\"center\"><a href=\"media.php?action=rename&amp;item=$this_item\" title=\"Rename $content\" class=\"rename_link\"><span>Rename</span></a></td>";
					} else {
						$list .= "<td></td><td></td>";
					}
					if($content != "thumbs"  && $content != "cache") {
						$list .= "<td class=\"center\"><a href=\"media.php?action=delete&amp;item=$this_item\" title=\"Delete $content\" class=\"delete_link\"><span>Delete</span></a></td>\n";
					} else {
						$list .= "<td></td>\n";
					}
				} else {
					$list .= "\n";
				}
				$list .= "\t\t</tr>\n";
				$alt_count++;
				$list .= drizzo_list_folder_contents_loop($folder . "/$content", $alt_count);
			}
		}
	}
	return $list;
}

function drizzo_upload_directories_dropdown($parent_dir = null) {
	$base_dir = str_replace("//","/",root_dir . 'drizzo-files' . $parent_dir);
	if($folder = opendir($base_dir)) {
		while(false !== ($file = readdir($folder))) {
			$dirs[] = $file;
		}
		closedir($folder);
	}
	if($parent_dir == null) {
		$parent_dir = basename($base_dir);
	}
	$dropdown = "<select name=\"save_location\" id=\"save_location\">\n";
	$dropdown .= "\t<option value=\"$parent_dir\" onclick=\"galleryMetaCheck('$parent_dir')\">" . str_replace('/','',$parent_dir) . "</option>\n";
	if($dirs) {
		$ignore = array($parent_dir,'cache','.','..');
		foreach($dirs as $dir) {
			if(is_dir($base_dir . "/" . $dir) && !in_array($dir,$ignore)) {
				$dropdown .= "\t<option value=\"$parent_dir/$dir\" onclick=\"galleryMetaCheck('$parent_dir/$dir')\">- $dir</option>\n";
				$dropdown .= drizzo_upload_directories_loop($parent_dir . "/" . $dir,$sub++);
			}
		}
	}
	$dropdown .= "</select>\n";
	return $dropdown; 
}

function drizzo_upload_directories_loop($parent_dir,$sub) {
	$base_dir = str_replace(array('drizzo-filesdrizzo-files','//'),array('drizzo-files','/'),root_dir . 'drizzo-files' . $parent_dir);
	$sub++;
	if($folder = opendir($base_dir)) {
		while(false !== ($file = readdir($folder))) {
			if($file != '.' && $file != '..') {
				$dirs[] = $file;
			}
		}
		closedir($folder);
	}
	$before = str_pad('',$sub,'-');
	if($dirs) {
		$ignore = array($parent_dir,'cache');
		foreach($dirs as $dir) {
			if(is_dir($base_dir . "/" . $dir) && !in_array($dir,$ignore)) {
				$dropdown .= "\t<option value=\"$parent_dir/$dir\" onclick=\"galleryMetaCheck('$parent_dir/$dir')\">-$before $dir</option>\n";
				$dropdown .= drizzo_upload_directories_loop($parent_dir . "/" . $dir,$sub);
			}
		}
	}
	return $dropdown;
}

function drizzo_media_update() {
	global $drizzo_gallery, $drizzo_posts;
	if(get_magic_quotes_gpc()) {
		$_GET['item'] = stripslashes($_GET['item']);
		$_POST['new_folder'] = stripslashes($_POST['new_folder']);
		$_POST['save_location'] = stripslashes($_POST['save_location']);
	}
	$this_item = $_GET['item'];
	$action = $_GET['action'];
	if(isset($_POST['name']) && get_magic_quotes_gpc()) {
		$name = stripslashes($_POST['name']) . "." . pathinfo($this_item,PATHINFO_EXTENSION);
	} elseif(isset($_POST['name'])) {
		$name = $_POST['name'] . "." . pathinfo($this_item,PATHINFO_EXTENSION);
	} elseif($_POST['title'] && get_magic_quotes_gpc()) {
		$name = stripslashes($_POST['title']) . "." . pathinfo($this_item,PATHINFO_EXTENSION);
	} elseif(isset($_POST['title'])) {
		$name = $_POST['title'] . "." . pathinfo($this_item,PATHINFO_EXTENSION);
	} else {
		$name = basename($this_item);
	}
	if(strlen($_POST['new_folder']) > 0) {
		$new_folder = $_POST['save_location'] . "/" . $_POST['new_folder'];
	} else {
		$new_folder = $_POST['save_location'];
	}
	if(is_dir($this_item)) {
		$new_location = str_replace("//","/",root_dir . $new_folder);
	} else {
		$new_location = str_replace("//","/",root_dir . $new_folder . "/" . $name);
	}
	if($this_item == $new_location) {
		return true;
	} elseif(is_file($this_item) && file_exists($new_location)) {
		return "<p class=\"alert\">A file named $name already exists at the specified location.</p>";
	} elseif(is_file($this_item) && !file_exists($new_location)) {
		$rename = rename($this_item,$new_location);
	} elseif(is_dir($this_item) && file_exists($new_location)) {
		$rename = true;
	} elseif(is_dir($this_item) && !file_exists($new_location)) {
		$rename = drizzo_mkdir($new_location);
	}
	if($rename) {
		if(is_dir($new_location)) {
			if($folder = opendir($this_item)) {
				while(false !== ($file = readdir($folder))) {
					if($file != "." && $file != "..") {
						$old_file = $this_item . "/" . $file;
						$new_file = $new_location . "/" . $file;
						rename($old_file,$new_file);
						$old_file = str_replace(root_dir,'',$old_file);
						$new_file = str_replace(root_dir,'',$new_file);
						$post_lookup = @mysql_query("SELECT `ID`,`content` FROM `$drizzo_posts` WHERE `content` LIKE '$old_file'");
						if(!mysql_errno() && @mysql_num_rows($post_lookup) > 0) {
							while($post = mysql_fetch_assoc($post_lookup)) {
								$new_content = str_replace($old_file,$new_file,$post['content']);
								@mysql_query("UPDATE `$drizzo_posts` SET `content`='$new_content' WHERE `ID`='$post[ID]'");
							}
						}
						if(strpos($new_location,"gallery") == true) {
							$gallery_check = @mysql_query("SELECT `ID` FROM `$drizzo_gallery` WHERE `path`='" . $this_item . "/" . $file . "'");
							if(!mysql_errno() && @mysql_num_rows($gallery_check) > 0) {
								while($row = mysql_fetch_assoc($gallery_check)) {
									@mysql_query("UPDATE `$drizzo_gallery` SET `path`='" . $new_location . "/" . $file . "' WHERE `ID`='$row[ID]'");
								}
							}
						}
					}
				}
				closedir($folder);
				rmdir($this_item);
			}
			$old_thumbs = str_replace('gallery','gallery/thumbs',$this_item);
			$new_thumbs = str_replace('gallery','gallery/thumbs',$new_location);
			if(file_exists($old_thumbs)) {
				if(!file_exists($new_thumbs)) {
					drizzo_mkdir($new_thumbs);
				}
				if($folder = opendir($old_thumbs)) {
					while(false !== ($file = readdir($folder))) {
						if($file != "." && $file != "..") {
							$old_thumb = $old_thumbs . "/" . $file;
							$new_thumb = $new_thumbs . "/" . $file;
							rename($old_thumb,$new_thumb);
							$post_lookup = @mysql_query("SELECT `ID`,`content` FROM `$drizzo_posts` WHERE `content` LIKE '$old_thumb'");
							if(!mysql_errno() && @mysql_num_rows($post_lookup) > 0) {
								while($post = mysql_fetch_assoc($post_lookup)) {
									$new_content = str_replace($old_thumb,$new_thumb,$post['content']);
									@mysql_query("UPDATE `$drizzo_posts` SET `content`='$new_content' WHERE `ID`='$post[ID]'");
								}
							}
						}
					}
					closedir($folder);
					rmdir($old_thumbs);
					$thumbs_moved = true;
				}	
			}
			$old_cache = str_replace('gallery','gallery/cache',$this_item);
			$new_cache = str_replace('gallery','gallery/cache',$new_location);
			if(file_exists($old_cache)) {
				if(!file_exists($new_cache)) {
					drizzo_mkdir($new_cache);
				}
				if($folder = opendir($old_cache)) {
					while(false !== ($file = readdir($folder))) {
						if($file != "." && $file != "..") {
							rename($old_cache . "/" . $file,$new_cache . "/" . $file);
						}
					}
					closedir($folder);
					rmdir($old_cache);
					$cache_moved = true;
				}	
			}
			$s = "s";
		} else {
			$old_file = str_replace(root_dir,'',$this_item);
			$new_file = str_replace(root_dir,'',$new_location);
			$post_lookup = @mysql_query("SELECT `ID`,`content` FROM `$drizzo_posts` WHERE `content` LIKE '$old_file'");
			if(!mysql_errno() && @mysql_num_rows($post_lookup) > 0) {
				while($post = mysql_fetch_assoc($post_lookup)) {
					$new_content = str_replace($old_file,$new_file,$post['content']);
					@mysql_query("UPDATE `$drizzo_posts` SET `content`='$new_content' WHERE `ID`='$post[ID]'");
				}
			}
			if(strpos($new_location,"gallery") == true) {
				$gallery_check = @mysql_query("SELECT `ID` FROM `$drizzo_gallery` WHERE `path`='" . $this_item . "'");
				if(!mysql_errno() && @mysql_num_rows($gallery_check) > 0) {
					while($row = mysql_fetch_assoc($gallery_check)) {
						@mysql_query("UPDATE `$drizzo_gallery` SET `path`='" . $new_location . "/" . $file . "' WHERE `ID`='$row[ID]'");
					}
				}
			}
			if(!file_exists(dirname(str_replace('gallery','gallery/thumbs',$new_location)))) {
				drizzo_mkdir(dirname(str_replace('gallery','gallery/thumbs',$new_location)));
			}
			if(file_exists(str_replace('gallery','gallery/thumbs',$this_item))) {
				$thumbs_moved = rename(str_replace('gallery','gallery/thumbs',$this_item),str_replace('gallery','gallery/thumbs',$new_location));
			}
			$old_thumb = str_replace(array(root_dir,'gallery'),array('','gallery/thumbs'),$this_item);
			$new_thumb = str_replace(array(root_dir,'gallery'),array('','gallery/thumbs'),$new_location);
			$post_lookup = @mysql_query("SELECT `ID`,`content` FROM `$drizzo_posts` WHERE `content` LIKE '$old_thumb'");
			if(!mysql_errno() && @mysql_num_rows($post_lookup) > 0) {
				while($post = mysql_fetch_assoc($post_lookup)) {
					$new_content = str_replace($old_thumb,$new_thumb,$post['content']);
					@mysql_query("UPDATE `$drizzo_posts` SET `content`='$new_content' WHERE `ID`='$post[ID]'");
				}
			}
			if(!file_exists(dirname(str_replace('gallery','gallery/cache',$new_location)))) {
				drizzo_mkdir(dirname(str_replace('gallery','gallery/cache',$new_location)));
			}
			if(file_exists(str_replace('gallery','gallery/cache',$this_item))) {
				$cache_moved = rename(str_replace('gallery','gallery/cache',$this_item),str_replace('gallery','gallery/cache',$new_location));
			}
			$s = null;
		}
		if($thumbs_moved && $cached_moved) {
			$response = "<p class=\"save\">$name, its cached image$s and its thumbnail$s were " . $action . "d.</p>";
		} elseif(!$thumbs_moved && $cached_moved) {
				$response = "<p class=\"save\">$name and its cached image$s were " . $action . "d.</p>";
		} elseif($thumbs_moved && !$cached_moved) {
				$response = "<p class=\"save\">$name and its thumbnail$s were " . $action . "d.</p>";
		} else {
			$response = "<p class=\"save\">$name was " . $action . "d.</p>";
		}
	} else {
		$response = "<p class=\"alert\">$name could not be " . $action . "d.</p>";
	}
	return $response;
}

function drizzo_media_save() {
	extract($_POST);
	if($new_folder != '') {
		if(get_magic_quotes_gpc()) {
			$new_folder = stripslashes($new_folder);
		}
		$new_folder = trim(preg_replace('/([\W])/','-',$new_folder));
		drizzo_mkdir(root_dir . $save_location . "/$new_folder");
		if(file_exists(root_dir . $save_location . "/$new_folder")) {
			$upload_dir = root_dir . $save_location . "/$new_folder/";
		} else {
			 return "<p class=\"alert\">The new folder could not be created.</p>";
		}
	} else {
		$upload_dir = root_dir . $save_location . "/";
	}
	if(is_writable($upload_dir)) {
		if(get_magic_quotes_gpc()) {
			$filename = stripslashes(basename($_FILES['file']['name']));
		} else {
			$filename = basename($_FILES['file']['name']);
		}
		if(!empty($_FILES['file']) && $_FILES['file']['error'] == 0) {
			$status = move_uploaded_file($_FILES['file']['tmp_name'],$upload_dir . $filename);
			if($status) {
				if($auto_thumb == 1) {
					$thumb_dir = str_replace(root_dir,'/',$upload_dir);
					$thumb = drizzo_gallery_make_thumbnail($thumb_dir,basename($_FILES['file']['name']),$_POST['thumb_width'],$_POST['thumb_height']);
				} elseif(!empty($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] == 0) {
					$thumb_save_location = str_replace("gallery","gallery/thumbs",$save_location);
					if($new_folder != '') {
						drizzo_mkdir(root_dir . $thumb_save_location . "/$new_folder");
						$thumb_save_location = root_dir . "$thumb_save_location/$new_folder";
					} else {
						$thumb_save_location = root_dir . "$thumb_save_location";
					}
					$thumb = move_uploaded_file($_FILES['thumbnail']['tmp_name'],$thumb_save_location . "/" . $filename);
				}
				if(substr_count($_FILES['file']['type'],"image") > 0) {
					global $drizzo_posts, $drizzo_gallery;
					$timestamp = time();
					$image_insert = @mysql_query("INSERT INTO `$drizzo_posts` (`type`,`status`,`title`,`content`,`comment_status`,`posted_date`,`author`,`tags`) VALUES('image','publish','$filename','','open','$timestamp','" . session_user_id . "','" . $_POST['tags'] . "')");
					$post_id = mysql_insert_id();
					if($post_id > 0) {
						$path = str_replace("//","/",$upload_dir . $filename);
						$gallery_insert = @mysql_query("INSERT INTO `$drizzo_gallery` (`post_id`,`path`) VALUES('$post_id','$path')");
						if(!mysql_errno()) {
							$db_insert = true;
						}
					}
				}
			}
		} else {
			return "<p class=\"alert\">There was an error uploading the file.</p>";
		}
		
		if($status) {
			$response = "<p class=\"save\">$filename ";
			if((!empty($_FILES['thumb']) || $auto_thumb == 1) && $thumb) {
				$response .= "and its thumbnail were ";
			} elseif((!empty($_FILES['thumb']) || $auto_thumb == 1) && !$thumb) {
				$response .= "but not its thumbnail was ";
			} else {
				$response .= "was ";
			}
			$response .= "saved";
			if($db_insert) {
				$response .= " and added to the database";
			}
			$response .= ".</p>\n";
		}
	} else {
		$response = "<p>The specified directory ($save_location) is not writable by the server</p>";
	}
	return $response;
}

function drizzo_media_delete() {
	global $drizzo_gallery, $drizzo_posts, $drizzo_comments;
	$this_item = $_GET['item'];
	if(is_file($this_item)) {
		$delete = unlink($this_item);
		if($delete) {
			if(strpos($this_item,'gallery') > 0) {
				if(file_exists(str_replace('gallery','gallery/cache',$this_item))) {
					$cache_delete = unlink(str_replace('gallery','gallery/cache',$this_item));
				}
				if(file_exists(str_replace('gallery','gallery/thumbs',$this_item))) {
					$thumb_delete = unlink(str_replace('gallery','gallery/thumbs',$this_item));
				}
				$db_id = @mysql_query("SELECT `post_id` FROM `$drizzo_gallery` WHERE `path` LIKE '$this_item%'");
				if(!mysql_errno()) {
					$post_id = @mysql_result($db_id,0);
				}
				echo $post_id;
				@mysql_query("DELETE FROM `$drizzo_gallery` WHERE `path`='$this_item'");
				echo mysql_error();
				@mysql_query("DELETE FROM `$drizzo_posts` WHERE `ID`='$post_id'");
				echo mysql_error();
				@mysql_query("DELETE FROM `$drizzo_comments` WHERE `post_id`='$post_id'");
				echo mysql_error();
			}
			$response = "<p class=\"trash\">" . basename($this_item);
			if($cache_delete && $thumb_delete && $db_delete) {
				$response .= ", its cached image, thumbnail and database entry have";
			} elseif(!$cache_delete && $thumb_delete && $db_delete) {
				$response .= ", its thumbnail and database entry have";
			} elseif($cache_delete && !$thumb_delete && $db_delete) {
				$response .= ", its cached image and database entry have";
			} elseif($cache_delete && $thumb_delete && !$db_delete) {
				$response .= ", its cached image and thumbnail entry have";
			} elseif(!$cache_delete && !$thumb_delete && $db_delete) {
				$response .= " and its database entry have";
			} elseif(!$cache_delete && $thumb_delete && !$db_delete) {
				$response .= " and its thumbnail have";
			} elseif($cache_delete && !$thumb_delete && !$db_delete) {
				$response .= " and its cached image have";
			} else {
				$response .= " has";
			}
			$response .= " been deleted.</p>";
		}
	} elseif(is_dir($this_item)) {
		$response = drizzo_media_delete_dir($this_item);
	}
	return $response;
}

function drizzo_media_delete_dir($dir) {
	if($folder = opendir($dir)) {
		while(false !== ($file = readdir($folder))) {
			$item = $dir . "/" . $file;
			if($file == '.' || $file == '..') {
				// Do Nothing
			} elseif(is_file($item)) {
				$delete = unlink($item);
				if($delete) {
					if(strpos('gallery',$item) !== false) {
						if(file_exists(str_replace('gallery','gallery/cache',$item))) {
							$cache_delete = unlink(str_replace('gallery','gallery/cache',$item));
						}
						if(file_exists(str_replace('gallery','gallery/thumbs',$item))) {
							$thumb_delete = unlink(str_replace('gallery','gallery/thumbs',$item));
						}
						$db_delete = @mysql_query("DELETE FROM `$drizzo_gallery` WHERE `path`='$item'");
					}
				}
			} elseif(is_dir($item)) {
				drizzo_media_delete_dir($item);
			}
		}
		closedir($folder);
		$delete_check = rmdir($dir);
	}
	if($delete_check) {
		$response = "<p class=\"trash\">" . basename($dir) . ", its contents and any related thumbnails, cached images and/or database entries have been deleted.</p>";
	} else {
		$response = "<p class=\"trash\">" . basename($dir) . " could not be deleted.</p>";
	}
	return $response;
}

function drizzo_media_replace() {
	$this_item = $_GET['item'];
	if($_POST['make_new_thumb']) {
		if(drizzo_gallery_make_thumbnail(dirname(str_replace(array(root_dir,'/thumbs'),array("/",''),$this_item)) . "/",basename($this_item),$_POST['thumb_width'],$_POST['thumb_height'])) {
			$response = "<p class=\"approve\">The thumbnail was replaced.</p><p><img src=\"$thumb\" alt=\"thumbnail\" /></p>";
		} else {
			$response = "<p class=\"alert\">The thumbnail could not be replaced.</p>";
		}
	} else {
		if(!empty($_FILES['new_file']) && $_FILES['new_file']['error'] == 0) {
			if(move_uploaded_file($_FILES['new_file']['tmp_name'],$this_item)) {
				$response = "<p class=\"save\">" . basename($this_item) . " has been replaced.</p>";
			} else {
				$response = "<p class=\"alert\">" . basename($this_item) . " could not be replaced.</p>";
			}
		} else {
			$response = "<p class=\"alert\">There was a problem uploading " . $_FILES['new_file']['name'] . ".</p>";
		}
	}
	return $response;
}
function drizzo_media_is_file_type($compare,$file) {
	if(is_file($file) && strpos(mime_content_type($file),$compare) !== false) {
		return true;
	} else {
		return false;
	}
}

if(!function_exists('mime_content_type')) { // From http://us3.php.net/mime_content_type
	function mime_content_type($f) {
		return trim(exec('file -bi ' . escapeshellarg($f)));
	}
}
?>
